package com.wandousoushu.jiusen.booksource.model

import com.wandousoushu.jiusen.booksource.data.entities.BookSource
import com.wandousoushu.jiusen.util.GsonUtils
import com.wandousoushu.jiusen.util.StringUtils
import java.util.*

/**
 * 所有书源
 */
class BookSourceManager {

    private val bookSourceList = HashMap<String, BookSource>()

    /**
     * 导入书源
     *
     * @param json
     * @return
     */
    fun importBookSourceFromJson(json: String?): List<BookSource> {
        var bookSources: MutableList<BookSource> = ArrayList() //书源
        if (StringUtils.isJsonArray(json)) {
            try {
                bookSources = GsonUtils.parseJArray(json, BookSource::class.java)
                return bookSources
            } catch (ignored: Exception) {
            }
        }
        if (StringUtils.isJsonObject(json)) {
            try {
                val bookSource = GsonUtils.parseJObject(json, BookSource::class.java)
                bookSources.add(bookSource)
                return bookSources
            } catch (ignored: Exception) {
            }
        }
        return bookSources
    }

    fun AddBookSource(bookSource: BookSource) {
        if (!bookSourceList.containsKey(bookSource.bookSourceUrl)) {
            bookSourceList[bookSource.bookSourceUrl] = bookSource
        }
    }

    fun AddBookSources(bookSources: List<BookSource>) {
        for (booksource in bookSources) {
            AddBookSource(booksource)
        }
    }

    fun getBookSource(url: String?): BookSource? {
        return bookSourceList[url]
    }

    fun getBookSourceList(): List<BookSource> {
        return ArrayList(bookSourceList.values)
    }

    fun clear() {

    }

    companion object {
        private val instance = BookSourceManager()
        fun GetInstance(): BookSourceManager {
            return instance
        }
    }
}